#include "core/WhitelistManager.h"
#include <QFile>
#include <QJsonDocument>
#include <QJsonArray>
#include <QTextStream>
#include <QDebug>

WhitelistManager::WhitelistManager()
{
}

WhitelistManager::~WhitelistManager() = default;

void WhitelistManager::loadDefaultWhitelist()
{
    loadSystemAPIs();
    loadThirdPartyLibraries();
}

bool WhitelistManager::loadFromFile(const QString &filePath)
{
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "Cannot open whitelist file:" << filePath;
        return false;
    }
    
    QTextStream in(&file);
    while (!in.atEnd()) {
        QString line = in.readLine().trimmed();
        if (!line.isEmpty() && !line.startsWith("#")) {
            m_whitelist.insert(line);
        }
    }
    
    file.close();
    return true;
}

bool WhitelistManager::saveToFile(const QString &filePath)
{
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "Cannot save whitelist file:" << filePath;
        return false;
    }
    
    QTextStream out(&file);
    out << "# Obfuscator Whitelist\n";
    out << "# Lines starting with # are comments\n\n";
    
    for (const QString &item : m_whitelist) {
        out << item << "\n";
    }
    
    file.close();
    return true;
}

void WhitelistManager::addToWhitelist(const QString &item)
{
    m_whitelist.insert(item);
}

void WhitelistManager::addToWhitelist(const QStringList &items)
{
    for (const QString &item : items) {
        m_whitelist.insert(item);
    }
}

void WhitelistManager::removeFromWhitelist(const QString &item)
{
    m_whitelist.remove(item);
}

bool WhitelistManager::isWhitelisted(const QString &item) const
{
    return m_whitelist.contains(item) || 
           m_systemAPIs.contains(item) || 
           m_thirdPartyLibs.contains(item);
}

QStringList WhitelistManager::getWhitelist() const
{
    QStringList list;
    list.append(m_whitelist.values());
    list.append(m_systemAPIs.values());
    list.append(m_thirdPartyLibs.values());
    return list;
}

void WhitelistManager::clear()
{
    m_whitelist.clear();
}

void WhitelistManager::loadSystemAPIs()
{
    loadiOSSystemAPIs();
    loadAndroidSystemAPIs();
}

void WhitelistManager::loadThirdPartyLibraries()
{
    loadCommonLibraries();
}

void WhitelistManager::loadiOSSystemAPIs()
{
    // iOS Foundation框架
    QStringList foundationClasses = {
        "NSObject", "NSString", "NSArray", "NSDictionary", "NSSet",
        "NSNumber", "NSData", "NSDate", "NSError", "NSURL",
        "NSURLSession", "NSURLRequest", "NSURLResponse",
        "NSNotification", "NSNotificationCenter",
        "NSUserDefaults", "NSBundle", "NSFileManager",
        "NSTimer", "NSThread", "NSOperationQueue"
    };
    
    // UIKit框架
    QStringList uikitClasses = {
        "UIApplication", "UIWindow", "UIView", "UIViewController",
        "UINavigationController", "UITabBarController",
        "UITableView", "UITableViewCell", "UICollectionView",
        "UILabel", "UIButton", "UITextField", "UITextView",
        "UIImageView", "UIImage", "UIScrollView",
        "UIAlertController", "UIAlertAction",
        "UIGestureRecognizer", "UITapGestureRecognizer"
    };
    
    // 重要的方法名
    QStringList methods = {
        "init", "initWithFrame", "initWithCoder",
        "dealloc", "viewDidLoad", "viewWillAppear", "viewDidAppear",
        "viewWillDisappear", "viewDidDisappear",
        "layoutSubviews", "drawRect", "setNeedsDisplay",
        "respondsToSelector", "performSelector",
        "addObserver", "removeObserver", "observeValueForKeyPath",
        "encodeWithCoder", "decodeWithCoder"
    };
    
    for (const QString &cls : foundationClasses) {
        m_systemAPIs.insert(cls);
    }
    for (const QString &cls : uikitClasses) {
        m_systemAPIs.insert(cls);
    }
    for (const QString &method : methods) {
        m_systemAPIs.insert(method);
    }
}

void WhitelistManager::loadAndroidSystemAPIs()
{
    // Android常见类
    QStringList androidClasses = {
        "Activity", "Fragment", "Service", "BroadcastReceiver",
        "ContentProvider", "Application", "Context",
        "View", "ViewGroup", "TextView", "Button", "EditText",
        "ImageView", "ListView", "RecyclerView",
        "Intent", "Bundle", "Handler", "AsyncTask"
    };
    
    for (const QString &cls : androidClasses) {
        m_systemAPIs.insert(cls);
    }
}

void WhitelistManager::loadCommonLibraries()
{
    // 常见第三方库
    QStringList libraries = {
        // iOS第三方库
        "AFNetworking", "Alamofire", "SDWebImage", "Masonry",
        "MBProgressHUD", "MJRefresh", "YYKit", "ReactiveObjC",
        
        // 通用库
        "RxSwift", "SnapKit", "Kingfisher", "SwiftyJSON",
        
        // Android第三方库
        "Retrofit", "OkHttp", "Glide", "Picasso",
        "ButterKnife", "EventBus", "RxJava", "Gson"
    };
    
    for (const QString &lib : libraries) {
        m_thirdPartyLibs.insert(lib);
    }
}